package com.autodatabase.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.autodatabase.database.DatabaseConnection;
import com.autodatabase.database.DatabaseUtil;
import com.autodatabase.json.JsonUtil;
import com.autodatabase.model.FactoryItemInfo;
import com.autodatabase.util.WebRequestUtil;
import com.autodatabase.xml.model.DatabaseFactoryXmlModel;
import com.autodatabase.xml.model.FactoryItemXmlModel;
import com.sun.org.apache.commons.beanutils.BeanUtils;

public class DBFactoryServer extends HttpServlet {
	public DBFactoryServer() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/plain;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		String op = request.getParameter("op");
System.err.println("---op:" + op);
		if("saveFactoryItem".equals(op)) {
			FactoryItemInfo finfo = WebRequestUtil.parseFactoryItem(request);
			DatabaseFactoryXmlModel model = DatabaseFactoryXmlModel.reload();
			FactoryItemXmlModel xmodel = new FactoryItemXmlModel();

			try {
				BeanUtils.copyProperties(xmodel, finfo);
				model.addItem(xmodel.getKey(), xmodel);
				model.write();
			} 
			catch(Exception e) {
				e.printStackTrace();
			}
		}
		else if("readFactoryItem".equals(op)) {
			String key = request.getParameter("id");
			
			//key为空说明是第一次查看factory列表
			if(key == null || "".equals(key)) {
				DatabaseFactoryXmlModel model = DatabaseFactoryXmlModel.reload();
				Collection list = model.getItems().values();
				String json = JsonUtil.factoryItemsToTree(list);
				PrintWriter out = response.getWriter();
		        out.println(json);
			}
			//key以factoryitem开头，说明正在展开factoryitem
			else if(key.startsWith("factoryitem")) {
				List<String> catalogs = DatabaseUtil.showDatabases(key);
				String json = JsonUtil.catalogsToTree(key, catalogs);
				PrintWriter out = response.getWriter();
		        out.println(json);
			}
			//key以catalog开头，说明正在展开数据库
			else if(key.startsWith("catalog")) {
				String fitemKey = key.substring(key.indexOf("^") + 1);
				String catalog = key.substring("catalog".length() + 1, key.indexOf("^"));
				List<String> tables = DatabaseUtil.showTables(fitemKey, catalog);
				String json = JsonUtil.tablesToTree(tables);
				PrintWriter out = response.getWriter();
		        out.println(json);
			}
		}
		else if("detailFactoryItem".equals(op)) {
			String key = request.getParameter("key");
			DatabaseFactoryXmlModel model = DatabaseFactoryXmlModel.getInstance();
			Map<String, FactoryItemXmlModel> items = model.getItems();

			if(items != null && items.size() > 0) {
				FactoryItemXmlModel itemModel = items.get(key);
				request.setAttribute("itemModel", itemModel);
				request.getRequestDispatcher("/page/newDatabaseFactory.jsp").forward(request, response);
			}
		}
		else if("deleteDBFactory".equals(op)) {
			String key = request.getParameter("key");
			DatabaseFactoryXmlModel model = DatabaseFactoryXmlModel.getInstance();
			Map<String, FactoryItemXmlModel> items = model.getItems();

			if(items != null && items.size() > 0) {
				FactoryItemXmlModel itemModel = items.remove(key);
				model.write();
			}
		}
		else if("testConnection".equals(op)) {
			FactoryItemInfo finfo = WebRequestUtil.parseFactoryItem(request);
			DatabaseConnection dcon = new DatabaseConnection(finfo);
			
			try {
				dcon.testConnection();
				PrintWriter out = response.getWriter();
		        out.println("success");
			}
			catch (Exception e) {
				e.printStackTrace();
				PrintWriter out = response.getWriter();
		        out.println(e.getMessage());
			}
		}
	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		filePath = config.getInitParameter("filePath");
		filePath = getServletContext().getRealPath(filePath);
		File store = new File(filePath);

		if(!store.exists()) {
			store.mkdir();
		}
	}
	
	private String filePath;
}
